package io.hepu.robotize.controller;

import io.hepu.robotize.auth.Jwts;
import io.hepu.robotize.base.BaseController;
import io.hepu.robotize.http.HttpResponse;
import io.hepu.robotize.model.Permission;
import io.hepu.robotize.model.User;
import io.hepu.robotize.service.IRoleService;
import io.hepu.robotize.service.ISysService;
import io.hepu.robotize.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController<User, String, IUserService> {
    @Resource
    private ISysService sysService;
    @Resource
    private IRoleService roleService;

    @Operation(summary = "获取用户主体信息", description = "返回用户主体信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "请求成功"),
            @ApiResponse(responseCode = "403", description = "禁止访问"),
            @ApiResponse(responseCode = "404", description = "对象不存在", content = @Content)
    })
    @GetMapping("/realm/{principal}")
    public HttpResponse<User> getUserRealm(@Parameter(description = "用户认证Token", required = true)
                                           @PathVariable("principal") String principal) throws Exception {
        String userId = Jwts.getSubject(principal);
        assert userId != null;
        User user = getService().findOne(userId);
        // 获取角色权重
        int priv = roleService.findPrivsByUserId(userId);
        user.setPrivilege(priv);
        return HttpResponse.success(user);
    }

    @Operation(summary = "获取用户权限信息", description = "返回用户权限信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "请求成功"),
            @ApiResponse(responseCode = "403", description = "禁止访问"),
            @ApiResponse(responseCode = "404", description = "对象不存在", content = @Content)
    })
    @GetMapping("/perms/{principal}")
    public HttpResponse<List<Permission>> getPermissions(@Parameter(description = "用户认证Token", required = true)
                                                         @PathVariable("principal") String principal) throws Exception {
        String userId = Jwts.getSubject(principal);
        assert userId != null;
        List<Permission> perms = sysService.findPermsByUserId(userId);
        return HttpResponse.success(perms);
    }
}
